package com.example.vector;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.graphics.Color;
import android.graphics.PointF;
import android.graphics.RectF;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;

import com.example.adapter.RecyclerAdapter;
import com.example.api.BaseApi;
import com.example.model.Farmer;
import com.example.model.PlantResult;
import com.example.model.Result;
import com.mapbox.geojson.Feature;
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.camera.CameraPosition;
import com.mapbox.mapboxsdk.camera.CameraUpdateFactory;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import com.mapbox.mapboxsdk.maps.Style;
import com.mapbox.mapboxsdk.style.expressions.Expression;
import com.mapbox.mapboxsdk.style.layers.FillLayer;
import com.mapbox.mapboxsdk.style.layers.LineLayer;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.fillColor;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.fillOpacity;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.lineColor;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.lineWidth;

public class MainActivity extends AppCompatActivity implements MapboxMap.OnMapClickListener {
    private MapboxMap map;
    private MapView mapView;
    private BaseApi baseApi;
    private String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhZG1pbiIsImNvbnRleHRVc2VySWQiOiIwIiwiY29udGV4dE5hbWUiOiLotoXnuqfnrqHnkIblkZgiLCJjb250ZXh0RGVwdElkIjoiMCIsImNvbnRleHRBcHBsaWNhdGlvbklkIjoiMCIsImlhdCI6MTYyNDQyODIxMCwiZXhwIjoxNjMzMDY4MjEwfQ.NCQ7wZbrcGk_4HBHwXHp7sFcetHTxrFLI_vYts8Sbqk";
    private LineLayer highLightLayer;
    private static final String CLICK_LAYER_NAME = "种植地块_点击";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Mapbox.getInstance(this, getString(R.string.mapbox_access_token));

        setContentView(R.layout.activity_main);


        mapView = (MapView) findViewById(R.id.mapView);
        mapView.onCreate(savedInstanceState);
        mapView.getMapAsync(new OnMapReadyCallback() {
            @Override
            public void onMapReady(@NonNull final MapboxMap mapboxMap) {
                map = mapboxMap;
                mapboxMap.setStyle(new Style.Builder().fromUri("asset://style.json"), new Style.OnStyleLoaded() {
                    @Override
                    public void onStyleLoaded(@NonNull Style style) {
                        //初始化地图位置
                        CameraPosition position = new CameraPosition.Builder()
                                .target(new LatLng(35.583627, 114.482722))
                                .zoom(16)
                                .build();
                        mapboxMap.setMaxZoomPreference(16.99);
                        mapboxMap.animateCamera(CameraUpdateFactory.newCameraPosition(position));
                        mapboxMap.addOnMapClickListener(MainActivity.this);

                        addClickLayer();
                        addHighLightLayer();
                    }
                });

            }
        });

        initHttp();

    }

    private void  showDialog( List<Farmer> list){
        if(list.size()==0){return;}
        View view = LayoutInflater.from(this).inflate(R.layout.dialog,null,false);
        final AlertDialog dialog = new AlertDialog.Builder(this).setView(view).create();
        RecyclerView recyclerView =view.findViewById(R.id.id_recyclerview);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(linearLayoutManager);
        // 用于描述item的适配器
        RecyclerAdapter recyclerAdapter = new RecyclerAdapter(list);
        recyclerView.setAdapter(recyclerAdapter);
        dialog.setCanceledOnTouchOutside(true);

        dialog.show();
        DisplayMetrics dm = new DisplayMetrics();
        WindowManager m = getWindowManager();
        m.getDefaultDisplay().getMetrics(dm);
        WindowManager.LayoutParams p =
                dialog.getWindow().getAttributes();
        if(p.height> (int) (dm.heightPixels * 0.5)){
            p.height = (int) (dm.heightPixels * 0.5); //高度设置为屏幕的1.0
            dialog.getWindow().setAttributes(p);
        }
    }

    /**
     * 添加高亮图层
     */
    private void addHighLightLayer() {
        LineLayer layer = (LineLayer) map.getStyle().getLayer("种植地块");
        LineLayer lineLayer = new LineLayer("种植地块_高亮", layer.getSourceId());
        lineLayer.setSourceLayer(layer.getSourceId());
        lineLayer.setProperties(
                lineColor(Color.parseColor("#ffff00")),
                lineWidth(5f));
        lineLayer.setFilter(Expression.eq(Expression.get("dkbm"),"1"));
        map.getStyle().addLayerAbove(lineLayer, layer.getId());
        highLightLayer=lineLayer;
    }

    /**
     * 添加点击图层
     */
    private void addClickLayer() {
        LineLayer layer = (LineLayer) map.getStyle().getLayer("种植地块");
        FillLayer fillLayer = new FillLayer(CLICK_LAYER_NAME, layer.getSourceId());
        fillLayer.setSourceLayer(layer.getSourceId());
        fillLayer.setProperties(
                fillColor(Color.parseColor("#ff69b4")),
                fillOpacity(0f));
        map.getStyle().addLayerAbove(fillLayer, layer.getId());


    }

    /**
     * 地图点击事件
     * @param point
     * @return
     */
    @Override
    public boolean onMapClick(@NonNull LatLng point) {
        PointF pointf = map.getProjection().toScreenLocation(point);
        RectF rectF = new RectF(pointf.x - 4, pointf.y - 4, pointf.x + 4, pointf.y + 4);
        List<Feature> featureList = map.queryRenderedFeatures(rectF, CLICK_LAYER_NAME);
        if (featureList.size() > 0) {
            for (Feature feature : featureList) {
                highLightLayer.setFilter(Expression.eq(Expression.get("dkbm"),feature.getStringProperty("dkbm")));
                queryFarmer(feature.getStringProperty("dkbm"));
            }
            return true;
        }
        return false;
    }

    /**
     * 初始化http请求
     */
    private void initHttp() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://gykj123.cn:8849/grandtech-open-platform-integrate-snxf/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        baseApi = retrofit.create(BaseApi.class);
    }

    /**
     * 查询农户信息
     * @param dkbm
     */
    private void queryFarmer(String dkbm){
        Map<String,String> map=new HashMap<>();
        map.put("code",dkbm);
        baseApi.getInfo(dkbm).enqueue(new Callback<Result>() {
            @Override
            public void onResponse(Call<Result> call, retrofit2.Response<Result> response) {
                Log.e("测试","成功");
                Log.e("测试", String.valueOf(response));

                if (response.body() != null && response.body().getData() != null) {
                    Log.e("测试", String.valueOf(response.body().getData().size()));
                    showDialog(response.body().getData());

                }else {
                    Log.e("测试", String.valueOf(response.message()));
                }
            }

            @Override
            public void onFailure(Call<Result> call, Throwable t) {
                Log.e("测试","失败");
            }
        });
    }
    @Override
    protected void onStart() {
        super.onStart();
        mapView.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mapView.onStop();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mapView.onLowMemory();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }


    public void showArea(View view) {
        Map<String,String> map=new HashMap<>();
        map.put("year","2021");
        map.put("areaCode","410526");
        map.put("cropCode","07");
        baseApi.getPlantArea(map).enqueue(new Callback<PlantResult>() {
            @Override
            public void onResponse(Call<PlantResult> call, Response<PlantResult> response) {
                Log.e("成功", String.valueOf(response));
                AlertDialog dialog = new AlertDialog.Builder(MainActivity.this).setTitle("面积统计").setMessage("滑县2021年冬小麦种植面积"+response.body().getData()+"亩").create();
                dialog.show();

            }

            @Override
            public void onFailure(Call<PlantResult> call, Throwable t) {

            }
        });


    }
}
